/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.wlclient.api;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.json.JSONException;
import org.json.JSONObject;

import com.worklight.wlclient.WLClientUtils;

/**
 * Extends WLResponse, contains errorCode codes and messages, 
 * in addition to the status in WLResponse. 
 * Contains the original response data object from the server as well.
 */
public final class WLProcedureInvocationFailResponse extends WLFailResponse {
	
	private static final String JSON_KEY_ERROR_MESSAGES = "errors";
	private JSONObject jsonResult;
	
	public WLProcedureInvocationFailResponse(HttpResponse httpResponse) {
		super(httpResponse);
	}
	
	public WLProcedureInvocationFailResponse(WLResponse response) {
		super(response);
	}

	public WLProcedureInvocationFailResponse(WLFailResponse response) {
		super(response);
		setErrorCode(response.getErrorCode());
		setErrorMsg(response.getErrorMsg());
	}

	public List<String> getProcedureInvocationErrors() {
		List<String> errors = new ArrayList<String>();
		try {
			if (getResult() != null && getResult().get(JSON_KEY_ERROR_MESSAGES) != null){
				errors = WLClientUtils.convertJSONArrayToList(getResult().getJSONArray(JSON_KEY_ERROR_MESSAGES));				
			}
		}
		catch (JSONException e){
			// Do Nothing here
		}
		return errors;
	}

	public JSONObject getResult() throws JSONException {
		if (jsonResult == null && responseText != null && responseText.length() > 0){
			jsonResult = WLClientUtils.convertStringToJSON(responseText);
		}		
		return jsonResult;
	}

	@Deprecated
	public JSONObject getJSONResult() throws JSONException {
		return getResult();
	}
}
